//
//  BCSearchResulfViewController.m
//  BangcaiBuy
//
//  Created by lsy on 16/6/13.
//  Copyright © 2016年 BCB. All rights reserved.
//

#import "BCSearchResulfViewController.h"
#import "BCSearchKeywordTitleCollectionViewCell.h"
#import "BCSearchKeywordCollectionViewCell.h"
#import "BCSearchHistoryTitleCollectionViewCell.h"
#import "BCSearchHistoryCollectionViewCell.h"
#import "BCSearchHistoryDeleteAllCollectionViewCell.h"
#import "BCStuffThirdCollectionViewCell.h"
#import "BCStuffInfoViewController.h"
#import "BCOrderViewController.h"
#import "SEARCHHISTORY+CoreDataProperties.h"

@interface BCSearchResulfViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate, actionDelegate,shopCarDelegate>
/** 搜索框绿色渐变背景视图 */
@property (nonatomic, strong) UIView *greenView;
@property (nonatomic, strong) UIButton *backButton;
//主视图
@property (nonatomic, strong) UICollectionView *mainCollectionView;
@property (nonatomic, strong) UIView *editBackgroundView;
@property (nonatomic, assign) BOOL isSearch;
@property (nonatomic, strong) NSArray *historyArray;
@property (nonatomic,strong) CALayer *dotLayer;
@property (nonatomic,assign) CGFloat endPointX;
@property (nonatomic,assign) CGFloat endPointY;
@property (nonatomic,strong) UIBezierPath *path;
@end

@implementation BCSearchResulfViewController

-(void)viewDidLoad {
    [super viewDidLoad];
    
    //隐藏导航栏
    
    _isSearch = NO;
    [self p_initTopView];
    [self p_initSearchView];
    [self p_initCollectionView];
    [self p_initHistoryList];
    [self p_initReddot];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    if (![BCShopCarManager sharedInstance].hidden) {
//        [[BCShopCarManager sharedInstance] hideShopWindow];
        [[BCShopCarManager sharedInstance] layOutWithLogo];
    }
    
    if (!self.rdv_tabBarController.tabBarHidden) {
        [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.rdv_tabBarController.tabBarHidden) {
        [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    }
}

/**
 *  初始化顶部视图view
 */
- (void)p_initTopView {
    
    self.greenView.frame = CGRectMake(0, 0, self.view.frame.size.width , 65.f);
    self.greenView.backgroundColor = BangcaiGreen;
    self.greenView.alpha = 0.95f;
    [self.view addSubview:self.greenView];
}

- (void)p_initCollectionView {
    UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.greenView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    self.mainCollectionView.backgroundColor = [UIColor whiteColor];
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    self.mainCollectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

    
    //设置contentInset属性（上左下右的值）
    self.mainCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 70, 0);
    self.mainCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mainCollectionView];
}

/**
 *  初始化搜索框view
 */
- (void)p_initSearchView {
    UIImageView *backImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BackArrow"]];;
    backImageView.frame = CGRectMake(17.5f, 30.f, 10.f, 20.f);
    [self.greenView addSubview:backImageView];

    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(0, 0, 40, 40);
    self.backButton.center = backImageView.center;
    [self.backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.greenView addSubview:self.backButton];
    
    UIView *searchIconBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 31.f, 21.f)];
    searchIconBGView.backgroundColor = [UIColor clearColor];
    
    UIImageView *searchIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"放大镜"]];
    searchIconView.frame = CGRectMake(5.f, 3.f, 15.f, 15.f);
    [searchIconBGView addSubview:searchIconView];
    
    UITextField *searchBar = [[UITextField alloc] initWithFrame:CGRectMake(45.f, 0, self.greenView.frame.size.width-45.f-16.f, 29.f)];
    searchBar.center = CGPointMake(searchBar.center.x, backImageView.center.y);
    searchBar.backgroundColor = [UIColor whiteColor];//[UIColor colorWithRed:0/255.f green:162.f/255.f blue:72.f/255.f alpha:1];
    searchBar.font = [UIFont boldSystemFontOfSize:13];
    searchBar.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    searchBar.borderStyle = UITextBorderStyleRoundedRect;
    searchBar.leftViewMode = UITextFieldViewModeAlways;
    searchBar.leftView = searchIconBGView;
    searchBar.placeholder = @"请输入想要搜索的内容";
    searchBar.returnKeyType = UIReturnKeySearch;
    searchBar.delegate = self;
    UIView *accessoryView = [[UIView alloc] initWithFrame:CGRectZero];
    searchBar.inputAccessoryView = accessoryView;
    [self.greenView addSubview:searchBar];
}

-(void)p_initHistoryList {
    self.historyArray = [[CoreDataStorageController sharedModel] selectElementFromEntity:@"SEARCHHISTORY" PredicateFromat:nil SortKey:@"timestamp" Limit:0 Ascending:NO];
}

-(void)p_initReddot {
    _endPointX = (SCREEN_WIDTH/3)+(SCREEN_WIDTH/6);
    _endPointY = SCREEN_HEIGHT+1000;
}

#pragma mark - action
-(void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Lazy
- (UIView *)greenView {
    if (_greenView == nil) {
        _greenView = [[UIView alloc] init];
    }
    return _greenView;
}

-(void)addHistory:(NSString *)stuff {
    NSArray *haveStoreStuffArray = [[CoreDataStorageController sharedModel] selectElementFromEntity:@"SEARCHHISTORY" PredicateFromat:[NSPredicate predicateWithFormat:@"text == %@",stuff] SortKey:nil Limit:0 Ascending:NO];
    if (!haveStoreStuffArray.count) {
        SEARCHHISTORY *model = [[CoreDataStorageController sharedModel] insertElementIntoEntity:@"SEARCHHISTORY"];
        model.timestamp = [NSDate date];
        model.text = stuff;
        [[CoreDataStorageController sharedModel] saveContext];
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (_isSearch) {
        return 1;
    }
    else {
        return 5;
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_isSearch) {
        return 10.f;
    }
    else {
        if (section == 0) {
            return 1;
        }
        else if (section == 1) {
            return 9;
        }
        else if (section == 2) {
            if (self.historyArray.count == 0) {
                return 0;
            }
            else {
                return 1;
            }
        }
        else if (section == 3) {
            return self.historyArray.count;
        }
        else {
            if (self.historyArray.count == 0) {
                return 0;
            }
            else {
                return 1;
            }
        }
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSearch) {
        static NSString *ID = @"StuffThirdCell";
        BCStuffThirdCollectionViewCell *cell = [BCStuffThirdCollectionViewCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        cell.name = [NSString stringWithFormat:@"松茸%ld斤一个", indexPath.row];
        cell.amount = 0;
        cell.price = 145.f;
        cell.minusHidden = NO;
        
        for (BCShopModel *stuff in [BCShopCarManager sharedInstance].stuffList) {
            if ([cell.name isEqualToString:stuff.name]) {
                cell.minusHidden = YES;
                cell.amount = stuff.amout;
            }
        }
        cell.delegate = self;
        
        __weak __typeof(&*cell)weakCell =cell;
        cell.reddot = ^() {
            CGRect parentRect = [weakCell convertRect:weakCell.plus.frame toView:self.view];
            [self JoinCartAnimationWithRect:parentRect];
        };

        return cell;
    }
    else {
        if (indexPath.section == 0) {
            static NSString *ID = @"KeywordTitleCell";
            BCSearchKeywordTitleCollectionViewCell *cell = [BCSearchKeywordTitleCollectionViewCell cellWithCollectionView:collectionView];
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
            return cell;
        }
        else if (indexPath.section == 1) {
            static NSString *ID = @"KeywordCell";
            BCSearchKeywordCollectionViewCell *cell = [BCSearchKeywordCollectionViewCell cellWithCollectionView:collectionView];
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
            switch (indexPath.row) {
                case 0:
                {
                    cell.keywordLable.text = @"培根肉";
                }
                    break;
                case 1:
                {
                    cell.keywordLable.text = @"高级小白菜";
                }
                    break;
                case 2:
                {
                    cell.keywordLable.text = @"哈尔滨红肠";
                }
                    break;
                case 3:
                {
                    cell.keywordLable.text = @"肋排牛肉";
                }
                    break;
                case 4:
                {
                    cell.keywordLable.text = @"酱牛肉";
                }
                    break;
                case 5:
                {
                    cell.keywordLable.text = @"红酒";
                }
                    break;
                case 6:
                {
                    cell.keywordLable.text = @"精品五花肉";
                }
                    break;
                case 7:
                {
                    cell.keywordLable.text = @"排骨(猪)";
                }
                    break;
                case 8:
                {
                    cell.keywordLable.text = @"红牛";
                }
                    break;
                    
                default:
                    break;
            }
            return cell;
        }
        else if (indexPath.section == 2) {
            static NSString *ID = @"HistoryTitleCell";
            BCSearchHistoryTitleCollectionViewCell *cell = [BCSearchHistoryTitleCollectionViewCell cellWithCollectionView:collectionView];
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
            return cell;
        }
        else if (indexPath.section == 3) {
            static NSString *ID = @"HistoryCell";
            BCSearchHistoryCollectionViewCell *cell = [BCSearchHistoryCollectionViewCell cellWithCollectionView:collectionView];
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
            SEARCHHISTORY *model = (SEARCHHISTORY *)self.historyArray[indexPath.row];
            cell.keywordLable.text = model.text;
            __weak typeof(self) weakSelf = self;
            cell.DeleteHistoryItem = ^(void){
                [[CoreDataStorageController sharedModel] removeElement:@[model]];
                weakSelf.historyArray = [[CoreDataStorageController sharedModel] selectElementFromEntity:@"SEARCHHISTORY" PredicateFromat:nil SortKey:@"timestamp" Limit:0 Ascending:NO];
                [weakSelf.mainCollectionView reloadData];
            };
            if (indexPath.row != 0) {
                cell.toplineImageView.hidden = YES;
                cell.leftlineImageView.hidden = YES;
                cell.rightlineImageView.hidden = YES;
                cell.leftlonglineImageView.hidden = NO;
                cell.rightlonglineImageView.hidden = NO;
            }
            else {
                cell.toplineImageView.hidden = NO;
                cell.leftlineImageView.hidden = NO;
                cell.rightlineImageView.hidden = NO;
                cell.leftlonglineImageView.hidden = YES;
                cell.rightlonglineImageView.hidden = YES;
            }
            return cell;
        }
        else {
            static NSString *ID = @"HistoryDeleteAllCell";
            BCSearchHistoryDeleteAllCollectionViewCell *cell = [BCSearchHistoryDeleteAllCollectionViewCell cellWithCollectionView:collectionView];
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
            return cell;
        }
    }
}

#pragma mark 刷新协议方法

- (void)reloadData
{
    [self.mainCollectionView reloadData];
    
}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{
    if (_isSearch) {
        UIEdgeInsets top = {5,5,5,5};
        return top;
    }
    else {
        if (section == 0) {
            UIEdgeInsets top = {10,0,0,0};
            return top;
        }
        else if (section == 1) {
            UIEdgeInsets top = {5,10,5,10};
            return top;
        }
        else if (section == 2) {
            UIEdgeInsets top = {20,0,10,0};
            return top;
        }
        else if (section == 3) {
            UIEdgeInsets top = {0,0,0,0};
            return top;
        }
        else {
            UIEdgeInsets top = {0,0,0,0};
            return top;
        }
    }
}

//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_isSearch) {
        return CGSizeMake(self.view.frame.size.width-10.f, 118.f);
    }
    else {
        if (indexPath.section == 0) {
            return CGSizeMake(self.view.frame.size.width, 35.f);
        }
        else if (indexPath.section == 1) {
            if ([UIScreen mainScreen].bounds.size.width < 414) {
                return CGSizeMake((self.view.frame.size.width-(10.f*4))/3, 45.f);
            }
            else {
                return CGSizeMake(124.f, 45.f);
            }
        }
        else if (indexPath.section == 2) {
            return CGSizeMake(self.view.frame.size.width, 35.f);
        }
        else if (indexPath.section == 3) {
            return CGSizeMake(self.view.frame.size.width-(10.f*2), 47.f);
        }
        else {
            return CGSizeMake(self.view.frame.size.width-(10.f*2), 58.f);
        }
    }
}

//每个item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if (_isSearch) {
        return 0;
    }
    else {
        if (section == 0) {
            return 0;
        }
        else if (section == 1) {
            return 10;
        }
        else if (section == 2) {
            return 0;
        }
        else if (section == 3) {
            return 0;
        }
        else {
            return 0;
        }
    }
}

//每个section中不同的行之间的行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    if (_isSearch) {
        return 5.f;
    }
    else {
        if (section == 0) {
            return 0;
        }
        else if (section == 1) {
            return 10.f;
        }
        else if (section == 2) {
            return 0;
        }
        else if (section == 3) {
            return 0;
        }
        else {
            return 0;
        }
    }
}

- (void)pushWithUUID:(NSString *)uuid
{
    
}

//collectionview点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSearch) {
        BCStuffInfoViewController *stuffInfoViewController = [[BCStuffInfoViewController alloc] init];
        stuffInfoViewController.stuff_uuid = @"345CF30E-E200-4E69-8D3E-084CFA0F7D01";
        [self.navigationController pushViewController:stuffInfoViewController animated:YES];
    }
    else {
        if (indexPath.section == 0) {
        }
        else if (indexPath.section == 1) {
            //结果
            _isSearch = YES;
            
            BCSearchKeywordCollectionViewCell *cell = (BCSearchKeywordCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
            [self addHistory:cell.keywordLable.text];
            
            self.mainCollectionView.backgroundColor = [UIColor colorWithRed:244.f/255.f green:244.f/255.f blue:244.f/255.f alpha:1];
            [self.mainCollectionView reloadData];
            
            [[BCShopCarManager sharedInstance] layOutWithLogo];
            [BCShopCarManager sharedInstance].delegate = self;
            self.mainCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 115, 0);
        }
        else if (indexPath.section == 2) {
        }
        else if (indexPath.section == 3) {
            //结果
            _isSearch = YES;
            self.mainCollectionView.backgroundColor = [UIColor colorWithRed:244.f/255.f green:244.f/255.f blue:244.f/255.f alpha:1];
            [self.mainCollectionView reloadData];
            
            [[BCShopCarManager sharedInstance] layOutWithLogo];
            [BCShopCarManager sharedInstance].delegate = self;
            self.mainCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 115, 0);
        }
        else {
            //清除历史
            [[CoreDataStorageController sharedModel] removeAllElements:@"SEARCHHISTORY"];
            self.historyArray = [[CoreDataStorageController sharedModel] selectElementFromEntity:@"SEARCHHISTORY" PredicateFromat:nil SortKey:@"timestamp" Limit:0 Ascending:NO];
            [self.mainCollectionView reloadData];
        }
    }

    NSLog(@"cell %@,%@ selected",@(indexPath.section),@(indexPath.row));
}

-(void)goTo {
}

- (void)logoTo
{
    BCOrderViewController *secondViewController = [[BCOrderViewController alloc] init];
    [self.navigationController pushViewController:secondViewController animated:YES];
    
}

#pragma mark - UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField {
    self.editBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    self.editBackgroundView.backgroundColor = [UIColor whiteColor];
    self.editBackgroundView.alpha = 0.85f;
    [self.view addSubview:self.editBackgroundView];
    [UIView animateWithDuration:0.1f animations:^{
        self.editBackgroundView.frame = CGRectMake(0, self.greenView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    [self.editBackgroundView removeFromSuperview];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    if ([textField.text isEqualToString:@""]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeCustomView;
        hud.labelText = @"请输入搜索内容";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    }
    else {
        [self addHistory:textField.text];
        
        [self.editBackgroundView removeFromSuperview];
        _isSearch = YES;
        self.mainCollectionView.backgroundColor = [UIColor colorWithRed:244.f/255.f green:244.f/255.f blue:244.f/255.f alpha:1];
        [self.mainCollectionView reloadData];
    }
    return YES;
}

#pragma mark -加入购物车动画
-(void) JoinCartAnimationWithRect:(CGRect)rect
{
    
    CGFloat startX = rect.origin.x;
    CGFloat startY = rect.origin.y;
    
    _path= [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointMake(startX, startY)];
    //三点曲线
    [_path addCurveToPoint:CGPointMake(_endPointX, _endPointY)
             controlPoint1:CGPointMake(startX, startY)
             controlPoint2:CGPointMake(startX - 180, startY - 200)];
    
    _dotLayer = [CALayer layer];
    _dotLayer.backgroundColor = [UIColor redColor].CGColor;
    _dotLayer.frame = CGRectMake(0, 0, 15, 15);
    _dotLayer.cornerRadius = (15 + 15) /4;
    [self.view.layer addSublayer:_dotLayer];
    [self groupAnimation];
    
}
#pragma mark - 组合动画
-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    
    CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"alpha"];
    alphaAnimation.duration = RedAnimationDuring;
    alphaAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    alphaAnimation.toValue = [NSNumber numberWithFloat:0.1];
    alphaAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,alphaAnimation];
    groups.duration = RedAnimationDuring+0.3f;
    groups.removedOnCompletion = NO;
    groups.fillMode = kCAFillModeForwards;
    groups.delegate = self;
    [groups setValue:@"groupsAnimation" forKey:@"animationName"];
    [_dotLayer addAnimation:groups forKey:nil];
    
    [self performSelector:@selector(removeFromLayer:) withObject:_dotLayer afterDelay:RedAnimationDuring+0.3f];
    
}
- (void)removeFromLayer:(CALayer *)layerAnimation{
    
    [layerAnimation removeFromSuperlayer];
}

@end
